package bTree.LeetCode;

public class 岛屿的周长 {
    int ans=0;
    int [][]dir=new int[][]{{1,0},{0,1},{-1,0},{0,-1}};
    public int islandPerimeter(int[][] grid) {
        int row=grid.length,line=grid[0].length;
        boolean [][]visited=new boolean[row][line];
        for(int i=0;i<row;i++){
            for(int j=0;j<line;j++){
                if(grid[i][j]==1){
                    dfs(i,j,grid,visited);
                    return ans;
                }
            }
        }
        return ans;
    }

    private void dfs(int i, int j, int[][] grid, boolean[][] visited) {
        visited[i][j]=true;
        for(int ii=0;ii<4;ii++){
            int nextX=i+dir[ii][0];
            int nextY=j+dir[ii][1];
            if(nextX<0||nextY<0||nextX>=grid.length||nextY>=grid[0].length||grid[nextX][nextY]==0){
                ans++;
                continue;
            }
            if(!visited[nextX][nextY]){
                dfs(nextX,nextY,grid,visited);
            }
        }
    }
}